#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智源研究院数据集成基础模块
"""

import json
import random
import logging
from datetime import datetime
from typing import Dict, List, Any, Optional

logger = logging.getLogger(__name__)

class ZhiyuanEducationDatabase:
    """智源研究院教育数据库"""
    
    def __init__(self):
        self.cognitive_development_data = self._load_cognitive_data()
        self.educational_psychology_data = self._load_psychology_data()
        self.learning_theory_data = self._load_learning_theory_data()
        self.child_development_data = self._load_child_development_data()
        self.narrative_psychology_data = self._load_narrative_psychology_data()
    
    def _load_cognitive_data(self):
        """加载认知发展数据"""
        return {
            "piaget_stages": {
                "sensorimotor": {
                    "age_range": "0-2岁",
                    "characteristics": ["感觉运动", "物体恒存性", "因果关系"],
                    "story_elements": ["简单动作", "重复模式", "感官体验"]
                },
                "preoperational": {
                    "age_range": "2-7岁", 
                    "characteristics": ["象征思维", "自我中心", "动画思维"],
                    "story_elements": ["拟人化角色", "魔法元素", "简单因果"]
                },
                "concrete_operational": {
                    "age_range": "7-11岁",
                    "characteristics": ["逻辑思维", "守恒概念", "分类能力"],
                    "story_elements": ["逻辑推理", "问题解决", "道德判断"]
                },
                "formal_operational": {
                    "age_range": "11岁以上",
                    "characteristics": ["抽象思维", "假设推理", "系统思考"],
                    "story_elements": ["复杂情节", "抽象概念", "哲学思考"]
                }
            },
            "attention_development": {
                "3-5岁": {
                    "attention_span": "5-10分钟",
                    "focus_type": "选择性注意",
                    "story_design": ["短小精悍", "视觉刺激", "互动频繁"]
                },
                "6-8岁": {
                    "attention_span": "10-20分钟", 
                    "focus_type": "持续注意",
                    "story_design": ["情节连贯", "角色发展", "适度复杂"]
                },
                "9-12岁": {
                    "attention_span": "20-30分钟",
                    "focus_type": "分配注意",
                    "story_design": ["多线索", "深度思考", "价值探讨"]
                }
            }
        }
    
    def _load_psychology_data(self):
        """加载教育心理学数据"""
        return {
            "motivation_theory": {
                "intrinsic_motivation": {
                    "factors": ["自主性", "胜任感", "关联性"],
                    "story_application": ["选择权", "成就感", "社会连接"]
                },
                "flow_theory": {
                    "conditions": ["明确目标", "即时反馈", "挑战平衡"],
                    "story_design": ["清晰任务", "及时回应", "难度适中"]
                }
            },
            "emotional_development": {
                "emotional_intelligence": {
                    "components": ["自我认知", "自我管理", "社会认知", "关系管理"],
                    "story_themes": ["情绪识别", "情绪调节", "同理心", "合作"]
                },
                "attachment_theory": {
                    "secure_attachment": ["安全感", "探索欲", "信任"],
                    "story_elements": ["可靠角色", "安全环境", "支持系统"]
                }
            }
        }
    
    def _load_learning_theory_data(self):
        """加载学习理论数据"""
        return {
            "constructivism": {
                "principles": ["主动建构", "先验知识", "社会互动"],
                "story_implementation": ["互动选择", "知识关联", "合作学习"]
            },
            "social_learning": {
                "mechanisms": ["观察学习", "模仿", "强化"],
                "story_models": ["榜样角色", "行为示范", "正面结果"]
            },
            "multiple_intelligences": {
                "types": {
                    "linguistic": "语言智能",
                    "logical": "逻辑数学智能", 
                    "spatial": "空间智能",
                    "musical": "音乐智能",
                    "bodily": "身体运动智能",
                    "interpersonal": "人际智能",
                    "intrapersonal": "内省智能",
                    "naturalist": "自然观察智能"
                },
                "story_adaptations": {
                    "linguistic": ["丰富词汇", "语言游戏", "诗歌韵律"],
                    "logical": ["逻辑推理", "数学概念", "因果关系"],
                    "spatial": ["视觉描述", "空间想象", "图形思维"],
                    "musical": ["节奏韵律", "音乐元素", "声音效果"],
                    "bodily": ["动作描述", "体感体验", "运动技能"],
                    "interpersonal": ["社交互动", "团队合作", "沟通技巧"],
                    "intrapersonal": ["自我反思", "情感探索", "价值观"],
                    "naturalist": ["自然观察", "环境保护", "生态系统"]
                }
            }
        }
    
    def _load_child_development_data(self):
        """加载儿童发展数据"""
        return {
            "language_development": {
                "3-4岁": {
                    "vocabulary": "1000-2000词",
                    "sentence_length": "3-4词",
                    "story_language": ["简单句式", "重复词汇", "具体描述"]
                },
                "5-6岁": {
                    "vocabulary": "2000-4000词",
                    "sentence_length": "4-6词", 
                    "story_language": ["复合句", "形容词", "时间概念"]
                },
                "7-8岁": {
                    "vocabulary": "4000-8000词",
                    "sentence_length": "6-8词",
                    "story_language": ["复杂句式", "抽象词汇", "逻辑连接"]
                }
            },
            "moral_development": {
                "kohlberg_stages": {
                    "preconventional": {
                        "age": "4-10岁",
                        "characteristics": ["避免惩罚", "获得奖励"],
                        "story_morals": ["明确规则", "直接后果", "权威指导"]
                    },
                    "conventional": {
                        "age": "10-13岁",
                        "characteristics": ["社会认同", "维护秩序"],
                        "story_morals": ["社会期望", "角色责任", "群体和谐"]
                    }
                }
            },
            "social_development": {
                "friendship_stages": {
                    "momentary_playmates": {
                        "age": "3-5岁",
                        "characteristics": ["共同活动", "物理接近"],
                        "story_focus": ["游戏伙伴", "分享玩具", "一起玩耍"]
                    },
                    "one_way_assistance": {
                        "age": "6-8岁", 
                        "characteristics": ["单向帮助", "满足需求"],
                        "story_focus": ["互相帮助", "解决问题", "支持朋友"]
                    },
                    "fair_weather_cooperation": {
                        "age": "9-12岁",
                        "characteristics": ["相互合作", "共同兴趣"],
                        "story_focus": ["深度友谊", "忠诚信任", "共同成长"]
                    }
                }
            }
        }
    
    def _load_narrative_psychology_data(self):
        """加载叙事心理学数据"""
        return {
            "story_structure": {
                "hero_journey": {
                    "stages": ["平凡世界", "冒险召唤", "拒绝召唤", "遇见导师", 
                              "跨越门槛", "试炼考验", "启示", "转变", "归来"],
                    "age_adaptations": {
                        "3-5岁": ["简化结构", "明确角色", "快速解决"],
                        "6-8岁": ["基本完整", "适度挑战", "成长主题"],
                        "9-12岁": ["完整结构", "复杂挑战", "深度成长"]
                    }
                },
                "narrative_elements": {
                    "character_development": ["性格特征", "成长弧线", "关系变化"],
                    "plot_devices": ["冲突设置", "转折点", "高潮解决"],
                    "themes": ["友谊", "勇气", "成长", "责任", "爱与关怀"]
                }
            },
            "therapeutic_storytelling": {
                "bibliotherapy": {
                    "principles": ["认同角色", "情感宣泄", "洞察获得", "行为改变"],
                    "applications": ["情绪调节", "行为矫正", "价值建立", "创伤治愈"]
                },
                "metaphorical_communication": {
                    "benefits": ["间接表达", "降低防御", "促进理解", "激发想象"],
                    "techniques": ["象征使用", "隐喻构建", "类比思维", "投射认同"]
                }
            }
        }
    
    def get_age_appropriate_content(self, age_group: str) -> Dict[str, Any]:
        """获取年龄适宜的内容指导"""
        age_mappings = {
            "3-5岁": "preoperational",
            "6-8岁": "concrete_operational", 
            "9-12岁": "concrete_operational"
        }
        
        stage = age_mappings.get(age_group, "preoperational")
        
        return {
            "cognitive_stage": self.cognitive_development_data["piaget_stages"][stage],
            "attention_span": self.cognitive_development_data["attention_development"].get(age_group, {}),
            "language_level": self.child_development_data["language_development"].get(age_group, {}),
            "moral_focus": self._get_moral_focus(age_group),
            "social_focus": self._get_social_focus(age_group)
        }
    
    def _get_moral_focus(self, age_group: str) -> Dict[str, Any]:
        """获取道德发展焦点"""
        if age_group in ["3-5岁", "6-8岁"]:
            return self.child_development_data["moral_development"]["kohlberg_stages"]["preconventional"]
        else:
            return self.child_development_data["moral_development"]["kohlberg_stages"]["conventional"]
    
    def _get_social_focus(self, age_group: str) -> Dict[str, Any]:
        """获取社交发展焦点"""
        social_stages = self.child_development_data["social_development"]["friendship_stages"]
        
        if age_group == "3-5岁":
            return social_stages["momentary_playmates"]
        elif age_group == "6-8岁":
            return social_stages["one_way_assistance"]
        else:
            return social_stages["fair_weather_cooperation"]